package com.ly.framework.web.service;

import com.alibaba.fastjson.JSONObject;
import com.ly.common.constant.Constants;
import com.ly.common.core.domain.model.LoginUser;
import com.ly.common.core.redis.RedisCache;
import com.ly.common.utils.http.HttpUtils;
import com.ly.system.service.ISysUserService;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 微信登录校验方法
 * 
 * @author sfli
 */
@Component
public class WxLoginService
{
    private static final Logger log = LoggerFactory.getLogger(WxLoginService.class);

    @Autowired
    private              TokenService tokenService;

    @Autowired
    private RedisCache redisCache;

    // appid
    @Value("${wx.appid}")
    private String appid;

    // appsecret
    @Value("${wx.appsecret}")
    private String appsecret;

    // 令牌有效期（默认30分钟）
    private int expireTime = 120;

    //url
    @Value("${wx.url}")
    private String url;

    @Autowired
    private ISysUserService userService;
    /**
     * 登录验证
     *
     * @param code 请求code
     * @return 结果
     */
    public String login(String code)
    {
        log.info(code);
        String rspStr = HttpUtils.sendGet(url, "appid=" + appid +  "&secret=" + appsecret + "&js_code=" + code + "&grant_type=authorization_code", Constants.GBK);

        JSONObject object = JSONObject.parseObject(rspStr);

        if(object.get("errcode")!=null){
            Integer errcode =  (Integer) object.get("errcode");
            if(0!=errcode){
                log.info("授权失败");
                return "error";
            }
        }

        // 请求，获取openid
        String openid = (String) object.get("openid");//用户唯一标识

        // 会话密钥session_key 是对用户数据进行加密签名的密钥。为了应用自身的数据安全，开发者服务器不应该把会话密钥下发到小程序，也不应该对外提供这个密钥。
        String session_key = (String) object.get("session_key");

        JSONObject wxUser = new JSONObject();
        wxUser.put("openid",openid);//获取接口调用凭证
        //wxUser.put("appid",appid);
        wxUser.put("session_key",session_key);

        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, code);
        redisCache.setCacheObject(code, wxUser,expireTime, TimeUnit.MINUTES);
        String token = tokenService.createToken(claims);
        return token;
    }
}
